#!/usr/bin/python3
# -*- coding: UTF-8 -*- 
# 设置utf-8  显示中文
"""
@Author: guo
@File：handle_response.py
"""
import sys

sys.path.append("../")

from common.yml.get_yml_keys import GetYmlKeys
from config.get_conf_data import GetConfData
from common.util.handle_jsonfile import HandleJsonFile

class HandleResponse:
    """"""
    def __init__(self):
        self.__ymlkeys = GetYmlKeys()
        self.__conf = GetConfData()
        self.__response_data = None
        self.__res = None
        self.__hjson = HandleJsonFile()

    def handle_response(self, res, ymldata: dict) -> None:
        """
        处理是否保存接口的响应结果
        :param res: 接口的响应结果
        :param ymldata: yml文件对应的数据(处理后的yml数据)
        """
        res = res
        ymldata = ymldata
        save_key = self.__ymlkeys.get_ensure_save_response_key()
        api_data_key = self.__ymlkeys.get_api_data_key()
        api_data = ymldata[api_data_key]
        save_value = api_data[save_key]
        # 当需要进行保存时，进行如下操作
        if save_value == True:
            response_key = self.__ymlkeys.save_response_key
            save_response = api_data[response_key]

            if save_response !=None:
                self.__res = res
                self.__response_data = save_response
                # 不同的type 进行不同的操作
                type_key = self.__ymlkeys.save_type_key
                save_type = save_response[type_key]
                json_str = self.__conf.get_json_str()
                sql_str = self.__conf.get_sql_str()
                all_str = self.__conf.get_all_str()

                if save_type == json_str:
                    self.__save_json()
                elif save_type == sql_str:
                    self.__save_sql()
                elif save_type == all_str:
                    self.__save_all()


    def __save_json(self):
        """
        当save_response的值不为None，说明response_filepath是有值的。因为当为None或非str类型时，
        直接将case置为了fail
        """
        res = self.__res
        data = self.__response_data
        filepath_key = self.__ymlkeys.get_response_filepath_key()
        filepath = data[filepath_key]

        if isinstance(res,dict):
            self.__hjson.write_dict_to_json_file(filepath,res)

        else:
            res = res.json()
            self.__hjson.write_dict_to_json_file(filepath,res)


    def __save_sql(self):
        """将结果保存到数据库中，这块的逻辑暂时未实现"""
        res = self.__res
        data = self.__response_data
        filepath_key = self.__ymlkeys.get_response_filepath_key()
        filepath = data[filepath_key]

        pass

    def __save_all(self):
        self.__save_json()
        self.__save_sql()









